package com.hdcx.Minfresh.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.hdcx.Minfresh.R;
import com.hdcx.Minfresh.alipay.PayResult;
import com.hdcx.Minfresh.alipay.SignUtils;
import com.hdcx.Minfresh.bean.UserInfoBean;
import com.hdcx.Minfresh.bean.ZhiFuBean;
import com.hdcx.Minfresh.url.MyUrl;
import com.hdcx.Minfresh.util.AppUtil;
import com.hdcx.Minfresh.util.ShpfUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/11/18.
 */

public class ChongzhiActivity extends BaseActivity {
    int pay = 1;//支付宝1 微信2
    LinearLayout[] layouts;
    ImageView[] imgs;
    TextView tv_money,tv_phone;
    EditText ed_money;
    String zhifu = "MIICWwIBAAKBgQDh4NU16/PEQe1ppLAkXPKyIjKHv6lNd+bbsgLe73oDGaoEmWKKTP71mB7mOWQpGXX6nYnuw8OhwzP2haI6Cm+2z9Nz5K7eOXcI5B5pFxFcpeqAzJXcFMl4SITfWDwwDpEnMWM447oEwuM61VvWXU8xNKGTJYWSj/vElnm7bi6FvQIDAQABAoGAPvgMuDGFDWtLoi3VJO38gohiCdH2grAwXYKspjWgkAixiwKvo9p/ITw9MPVC5OpCJ5GPiE5u1UOz0r/CT+fk6E3FRgSdL17kLPG0S6+umHDOofweChjLwEkD74ImRQ6rbEsm8IhXEsNmtiiGJkkertQG398ymLKXEbV2PrT3GAkCQQDz2DYhMWPhNfF4BwF5Ip6xmJg5bM+9DS5BfAxngx4KgulhH2AOQWANygdjdFA1fPqT/KnrjyO6K123rwHy+PGzAkEA7SNYwJ1lxiSfD3uD6+tu9n2kmx5skNKb9YtaUs9x2FTSFLXo0VRH22L+miux/tYcBdC2z2Fm//cu17sAK0mSzwJAPmlKgXhovg3WfggdAmov//i0jY4iJZsoCa68ZgoTOFGFdkxXg46MDTt2ZKgyl14jrJjwzM/YLyBGXms2rn+1LQJAC2QDQ11MIjRoH4pDT/XDIrvuSDUx6dL0Attqv0ePpGCOpsgGIuf1e6hJqoYmyqLmPbFE1rlLBUiOS3aED5A9KQJAJQ4mceYofgkNqIO07EvQh8gXrLDOyP+2zq40touxoe8qEXZJFXcFOzXTrUD0sua6hl/KISuI4dWhNTopULA71A==";


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_mycount);
        initView();
        initData();
    }

    private void initView() {
        TextView title = (TextView) findViewById(R.id.tv_title);
        tv_phone = (TextView) findViewById(R.id.tv_phone);
        title.setText("我的钱包");
        findViewById(R.id.tv_left).setOnClickListener(this);
        findViewById(R.id.bt_cz).setOnClickListener(this);
        layouts = new LinearLayout[]{(LinearLayout) findViewById(R.id.layout_zhifubao), (LinearLayout) findViewById(R.id.layout_weixin)};
        imgs = new ImageView[]{(ImageView) findViewById(R.id.img_zhifubao), (ImageView) findViewById(R.id.img_weixin)};
        tv_money = (TextView) findViewById(R.id.tv_money);
        ed_money = (EditText) findViewById(R.id.ed_money);
        for (int i = 0; i < layouts.length; i++) {
            final int finalI = i;
            layouts[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    imgs[pay - 1].setImageResource(R.drawable.ic_quan);
                    pay = finalI + 1;
                    imgs[pay - 1].setImageResource(R.drawable.ic_gou);
                }
            });
        }
    }

    private void initData() {
        String money = getIntent().getStringExtra("money");
        tv_money.setText("当前余额:"+money+"元");
        UserInfoBean loginData = ShpfUtil.getObject(ShpfUtil.LOGIN);
        tv_phone.setText("当前账号："+loginData.getUserinfo().getMobile());
    }


    /*   参数
       uid		//用户id 20
       amount  //充值金额
       pay   //支付方式  1支付宝 2微信*/
    private void upload() {
        if (ed_money.getText().toString().trim().equals("")) {
            Toast.makeText(this, "请输入正确的金额!", Toast.LENGTH_SHORT).show();
            return;
        }
        AppUtil.showLoading(this);
        JSONObject json = new JSONObject();
        try {
            json.put("uid", AppUtil.getUserId());
            json.put("amount", ed_money.getText().toString().trim());
            json.put("pay", pay);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils.postString()
                .url(MyUrl.USERMONEYORDER)
                .content(json.toString())
                .build()
                .execute(new Callback<ZhiFuBean>() {
                    @Override
                    public ZhiFuBean parseNetworkResponse(Response response) throws IOException {
                        String json = response.body().string();
                        return new Gson().fromJson(json, ZhiFuBean.class);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        AppUtil.closeLoading();
                    }

                    @Override
                    public void onResponse(ZhiFuBean response) {
                        AppUtil.closeLoading();
                        if (response.getStatus() == 1) {
                            if (pay == 1) {
                                pay_zhifubao(response, ChongzhiActivity.this);
                            } else {

                            }
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_left:
                finish();
                break;
            case R.id.bt_cz:
                upload();
                break;
        }
    }

    /**
     * 支付宝支付
     * call alipay sdk pay. 调用SDK支付
     */
    public void pay_zhifubao(ZhiFuBean response, final FragmentActivity mActivity) {
        // 订单
        String orderInfo;
        // 签约合作者身份ID
        orderInfo = "partner=" + "\"" + response.getOrder().getPay().getPartner() + "\"";
        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + response.getOrder().getPay().getSeller_email() + "\"";
        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + response.getOrder().getOrder_sn() + "\"";
        // 商品名称
        orderInfo += "&subject=" + "\"" + response.getOrder().getPay().getPayment_name() + "\"";
        // 商品详情
        orderInfo += "&body=" + "\"" + "充值"+response.getOrder().getAmount()+"元" + "\"";
        // 商品金额
        orderInfo += "&total_fee=" + "\"" + response.getOrder().getAmount() + "\"";
        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + response.getOrder().getPay().getNotify_url() + "\"";
        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";
        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";
        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";
        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";
        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";
        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";
        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";
        // 对订单做RSA 签名
        String sign = SignUtils.sign(orderInfo, AppUtil.zhifu);
        // 仅需对sign 做URL编码
        if (sign != null) {
            try {
                sign = URLEncoder.encode(sign, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        // 完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + "sign_type=\"RSA\"";


        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                Looper.prepare();
                PayTask alipay = new PayTask(ChongzhiActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo);

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                new MyHandler(ChongzhiActivity.this).sendMessage(msg);
                Looper.loop();
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    static class MyHandler extends Handler {
        private FragmentActivity mActivity;

        MyHandler(FragmentActivity mActivity) {
            this.mActivity = mActivity;
        }


        @Override
        public void handleMessage(Message msg) {
            PayResult payResult = new PayResult((String) msg.obj);
            // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
            String resultInfo = payResult.getResult();
            String resultStatus = payResult.getResultStatus();
            // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
            //can_upload =true;
            if (TextUtils.equals(resultStatus, "9000")) {
                Toast.makeText(mActivity, "支付成功", Toast.LENGTH_SHORT).show();
                //AppUtil.is_frash = true;
//                }
                mActivity.finish();
                mActivity.setResult(RESULT_OK);
            } else {

                // 判断resultStatus 为非“9000”则代表可能支付失败
                // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                if (TextUtils.equals(resultStatus, "8000")) {
                    Toast.makeText(mActivity, "支付结果确认中", Toast.LENGTH_SHORT).show();
                } else {
                    // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                    Toast.makeText(mActivity, "支付取消", Toast.LENGTH_SHORT).show();
                }
                mActivity.setResult(6001);
            }
        }
    }
}
